(function(global){
	var Peizi = function(type, amount, num, numMulti, dd){
		// 利率
		this.intPerDayEveryWan = 12;
		this.intPerMonthPercent = 0.013;

		this.type = type;
		this.typeStr = type == 'month' ? '月' : '天';

		this.amount = amount;
		this.num = num;
		this.numMulti = numMulti;

		// 创建时间
		dd = dd ? moment(dd) : moment();
		this.dayCreated = dd.format('YYYY-MM-DD');

		var dayBegin = dd.add(1, 'day');
		while(dayBegin.day() == 6 || dayBegin.day() == 0){
			dayBegin.add(1, 'day');
		}

		this.dayBegin = dayBegin.format('YYYY-MM-DD');
	};

	Peizi.prototype.cal = function(){
		this.amountTotal = this.amount * (this.numMulti + 1);

		this.amountWarning = Math.floor(this.amountTotal * 0.65)
		this.amountFlush = Math.floor(this.amountTotal * 0.52);

		this.intPerMonth = Math.ceil(this.numMulti * this.amount * this.intPerMonthPercent) || 1;
		this.amountInt = this.intPerMonth * this.num;

		this.amountIntStr = '{0}元/月 * {1}月 = 合计{2}'.format(this.intPerMonth, this.num, this.amountInt);

		if('day' == this.type){
			// 1万1天11块，2万1天22...
			var wanNum = Math.ceil(this.numMulti * this.amount / 10000) || 1;
			this.intPerDay = wanNum * this.intPerDayEveryWan;
			this.amountInt = this.intPerDay * this.num;
			this.amountIntStr = '{0}元/天 * {1}天 = 合计{2}'.format(this.intPerDay, this.num, this.amountInt);
		}
	};
	
	global.Peizi = Peizi;
})(this);

(function(global, Yo, YoPages){
	var Section = Yo.Section;
	var User = Yo.User;
	var Utils = Yo.Utils;
	var Req = Yo.Req;

	var Peizi = global.Peizi;

	var authUrl = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid={0}&redirect_uri={1}&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect';
	var redirectUrl = 'http://tech11.cn/wx/ind/peizi/index?showwxpaytitle=1';
	Section.authUrl = authUrl.format('wx9f7507a78aa0c8f0', encodeURIComponent(redirectUrl));

	function showUser(user){
		$('#userNickname').text(user.nickname);
		$('#userHeaderImg').attr('src', user.headimgurl);
	}

	// main page
	YoPages.initPages.push(function(){
		User.remove();

		// user
		var user = global.userSaved;
		if(user){
			User.set(user);
			showUser(user);
		}else{
			User.remove();
			document.location.href = Section.authUrl;
		}

		var lastCal = {};
		// 金额、利息计算
		var cal = function(type){
			if(!type){
				var typeChoose = $('#pz-type .control-item');
				type = typeChoose.index(typeChoose.filter('.active')) == 0 ? 'month' : 'day';
			}

			var amount = $('#amount').val();
			if(!amount){
				lastCal = {};
				return;
			}
			amount = parseInt(amount);

			// 默认一天、月
			var num = $('#num').val();
			if(!num)
				num = '1';
			num = parseInt(num);

			// 默认配资一倍
			var numMulti = $('#numMulti').val();
			if(!numMulti)
				numMulti = '1';
			numMulti = parseInt(numMulti);

			var pz = new Peizi(type, amount, num, numMulti);
			pz.cal();

			$('#pzDayRange').text('' + pz.num + pz.typeStr);
			$('#pzDayBegin').text(pz.dayBegin);

			$('#pzAmountTotal').text(pz.amountTotal);
			$('#pzAmountWarning').text(pz.amountWarning);
			$('#pzAmountFlush').text(pz.amountFlush);

			$('#pzAmountInt').text(pz.amountIntStr);
			$('#totalPayed').text(pz.amount + pz.amountInt);

			lastCal.amount = amount;
			lastCal.type = type;
			lastCal.num = num;
			lastCal.numMulti = numMulti;
		};

		$('#pz-type .control-item').click(function(e){
			var type = $(e.target).attr('data-type');
			cal(type);
		});
		$('#amount,#num,#numMulti').change(function(e){
			var type = $(e.target).attr('data-type');
			cal();
		});

		// pay
		$('#btn-pay').click(function(){
			cal();

			if(!lastCal.amount){
				alert('请先输入本金和时间长度！');
				return;
			}

			if(lastCal.amount < 100){
				alert('本金金额不能小于100！');
				return;
			}

			var user = User.get();
			lastCal.openid = user.openid;

			Req.post('/wx/ind/peizi/apply', lastCal, function(data){
				if(data.flag){
					Yo.log.debug(data);
					wx.chooseWXPay({
						timestamp: data.timeStamp, 
						nonceStr: data.nonceStr, 
						package: data.package, 
						signType: data.signType, 
						paySign: data.paySign, 
						success: function (res) {
							Section.go('apply-list');
						}
					});
				}else{
					if(data.msg){
						alert(data.msg);
						return;
					}

					if('amount-required' == data.tips){
						alert('参数错误！');
					}else if('amount-rangeout' == data.tips){
						alert('本金必须在0-50000之间！');
					}else if('multi-rangeout' == data.tips){
						alert('配资倍数必须在1-5之间！');
					}else if('num-rangeout' == data.tips){
						alert('配资时间必须在1-50之间（最多50天或50个月）！');
					}else if('person-info' == data.tips){
						Section.go('person-info');
						alert('请先完善个人信息！');
					}else if('wx-order-failed' == data.tips){
						alert('创建微信支付订单失败，请联系客服人员！');
					}
				}
			});
		});

	});

	// person user info
	YoPages.initPages.push(function(){
		Section.addPageFn('person-info', function(){
			var user = User.get();
			var openid = user.openid;

			Req.get('/wx/ind/peizi/get-user-info', {openid: openid}, function(data){
				if(!data.flag){
					alert(data.msg);
					return;
				}

				var user = data.user;
				if(!user)
					return;

				$('#userId').text(user.idcardNo || '--');
				$('#userName').text(user.name || '--');
				$('#userTel').text(user.tel || '--');

				var preDir = '/wx/ind/peizi/img-show?serverId=';
				if(user.idcardPic){
					$('#userIdPic').attr('src', preDir + user.idcardPic);
				}
				if(user.idcardPic2){
					$('#userIdPic2').attr('src', preDir + user.idcardPic2);
				}
			});
		});

		// *** 个人信息身份证图片上传
		$('#btn-choose-idcard-pic,#btn-choose-idcard-pic2').click(function(){
			var user = User.get();
			var openid = user.openid;

			var isPic2 = $(this).attr('id').indexOf('pic2') != -1;
			wx.chooseImage({
				success: function(res){
					var localIds = res.localIds;
					if(!localIds.length)
						return;

					var localId = localIds[0];

					wx.uploadImage({
							localId: localId, 
							isShowProgressTips: 1, 
							success: function(res){
								var serverId = res.serverId;
								Yo.log.i('upload image result - ' + serverId);

								var preDir = '/wx/ind/peizi/img-show?serverId=';
								if(isPic2){
									$('#userIdPic2').attr('src', preDir + serverId);
								}else{
									$('#userIdPic').attr('src', preDir + serverId);
								}

								var params = {openid: openid, serverId: serverId};
								params.type = 'userId';
								params.isPic2 = isPic2;

								Req.post('/wx/ind/peizi/update-user-info', params, function(data){
								});
							}
					});
				}
			});			
		});

		// *** 个人信息修改按钮事件
		Yo.role('change-user-info').click(function(){
			$('#person-info form').hide();

			var field = $(this).attr('data-field');
			$('#form-' + field).show();

			var val = $(this).siblings('dd').text();
			if(val && val != '--')
				$('#input-' + field).val(val);

			$('#input-' + field).focus();
			$('#person-info .content')[0].scrollTop = 200;
		});

		// *** 修改身份证号码
		$('#btn-confirm-user-id').click(function(){
			var userId = $('#input-user-id').val();
			var isOk = /(^\d{15}$)|(^\d{17}([0-9]|X)$)/.test(userId.toUpperCase());
			if(!isOk){
				alert('请输入正确的身份证号码！');
				return;
			}

			var user = User.get();
			var openid = user.openid;

			var params = {};
			params.type = 'idcardNo';
			params.openid = openid;
			params.idcardNo = userId;

			Req.post('/wx/ind/peizi/update-user-info', params, function(data){
				if(data.flag){
					$('#userId').text(userId);
					$('#form-user-id').hide();
				}else{
					alert(data.msg);
				}
			});
		});

		// *** 修改真实姓名
		$('#btn-confirm-user-name').click(function(){
			var userName = $('#input-user-name').val();
			var isOk = userName.length >= 2;
			if(!isOk){
				alert('请输入您的真实姓名！');
				return;
			}

			var user = User.get();
			var openid = user.openid;

			var params = {};
			params.type = 'userName';
			params.openid = openid;
			params.userName = userName;

			Req.post('/wx/ind/peizi/update-user-info', params, function(data){
				if(data.flag){
					$('#userName').text(userName);
					$('#form-user-name').hide();
				}else{
					alert(data.msg);
				}
			});
		});

		// *** 发送手机验证码
		$('#btn-send-verify-code').click(function(){
			var userTel = $('#input-user-tel').val();
			var isOk = /^\d{11}$/.test(userTel);
			if(!isOk){
				alert('请输入您的手机号码！');
				return;
			}

			var params = {};
			params.userTel = userTel;

			Req.get('/wx/ind/peizi/send-tel-verify-code', params, function(data){
				if(data.flag){
					// wait 30 seconds TODO
					var totalSeconds = 30;
					$('#btn-send-verify-code').attr('disabled', 'disabled').find('span').text('' + totalSeconds).show();
					Section.intervalSendVerifyCode = setInterval(function(){
						var sp = $('#btn-send-verify-code span');
						var txt = sp.text();
						if(!txt)
							return;

						var counted = parseInt(txt) - 1;

						if(counted == 0){
							sp.text('').hide();
							$('#btn-send-verify-code').removeAttr('disabled');

							clearInterval(Section.intervalSendVerifyCode);
						}else{
							sp.text(counted);
						}
					}, 1000);
				}else{
					alert(data.msg);
				}
			});
		});

		// *** 修改手机号
		$('#btn-confirm-user-tel').click(function(){
			var userTel = $('#input-user-tel').val();
			var userTelVerifyCode = $('#input-user-tel-verify-code').val();

			var isOk = /^\d{11}$/.test(userTel);
			if(!isOk){
				alert('请输入您的手机号码！');
				return;
			}

			isOk = /^\d{4}$/.test(userTelVerifyCode);
			if(!isOk){
				alert('请输入4为数字验证码！');
				return;
			}

			var user = User.get();
			var openid = user.openid;

			var params = {};
			params.type = 'userTel';
			params.openid = openid;
			params.userTel = userTel;
			params.userTelVerifyCode = userTelVerifyCode;

			Req.post('/wx/ind/peizi/update-user-info', params, function(data){
				if(data.flag){
					$('#userTel').text(userTel);
					$('#form-user-tel').hide();
				}else{
					if(data.msg){
						alert(data.msg);
					}else{
						if('verify-code-expired' == data.tips){
							alert('验证码不正确或已经失效，请重新获取！');

//							$('#btn-send-verify-code').removeAttr('disabled').find('span').text('').hide();
//							if(Section.intervalSendVerifyCode){
//								clearInterval(Section.intervalSendVerifyCode);
//							}
						}
					}
				}
			});
		});

	});

	// apply list
	YoPages.initPages.push(function(){
		Section.addPageFn('apply-list', function(){
			var user = User.get();
			var openid = user.openid;

			var statusLabels = {
				1: '未支付',
				10: '已经支付', 
				20: '审核中',
				30: '通过审核', 
				40: '已经配资'
			};

			Req.get('/wx/ind/peizi/get-apply-list', {openid: openid}, function(data){
				if(!data.ll)
					return;

				_.each(data.ll, function(it){
					var pz = new Peizi(it.type, it.amount, it.num, it.numMulti, it.dd);
					pz.cal();

					it.dayCreated = pz.dayCreated;
					it.dayBegin = pz.dayBegin;

					it.typeStr = pz.typeStr;

					it.amountTotal = pz.amountTotal;
					it.amountWarning = pz.amountWarning;
					it.amountFlush = pz.amountFlush;

					it.amountIntStr = pz.amountIntStr;

					it.statusLabel = statusLabels[it.status];
				});

				var tpl = $('#tplApplyItemList').html();
				var html = Yo.format(tpl, data);
				$('#apply-list-content').html(html);
			});
		});
	});

})(this, Yo, YoPages);
